package com.kaifamiao.orm.dao;

import com.kaifamiao.orm.entity.Customer;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import java.util.List;

public class CustomerDao {

    private Session session ;

    public void init( Session session ){
        this.session = session ;
    }

    public Integer save( Customer c ) {
        // 仅获得事务对象
        Transaction transaction = session.getTransaction();
        // 开启事务
        transaction.begin();
        Integer id = ( Integer)session.save( c );
        // 提交事务
        transaction.commit();
        return id ;
    }

    public void update( Customer c ) {
        session.getTransaction().begin();
        session.update( c );
        session.getTransaction().commit();
    }

    public void delete( Integer id ) {
        Customer c = session.find( Customer.class , id );
        session.getTransaction().begin();
        session.delete( c );
        session.getTransaction().commit();
    }

    public Customer find( Integer id ) {
        return session.find( Customer.class , id );
    }

    // 使用 HQL 进行查询 ( HQL: Hibernate Query Language )
    public List<Customer> findAll() {
        // 其中 Customer 表示实体类的类名，id 表示实体类中的属性
        String hql = "FROM Customer c ORDER BY c.id" ;
        Query query = session.createQuery( hql );
        List<Customer> customers = query.list();
        return customers ;
    }

}
